const webpack = require('webpack');
const path = require('node:path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
// const Dotenv = require('dotenv-webpack');
const paths = require('./webpack/paths');
// import webpack from 'webpack'
const CurEnv = process.env.ENV;
// const env = {
//   ENV: CurEnv
// };
console.log('config-env', CurEnv);
// const env = require('dotenv').config({ path: 'config/envs/.env.' + CurEnv });
// console.log('config-env', env);
require('dotenv').config();
// const NodePolyfillPlugin = require('node-polyfill-webpack-plugin');
// console.log('webpack-process.env', process.env);
// const localEnv = require('dotenv').config({ path: path.resolve(__dirname, '.env.local') });
require('dotenv').config({ path: path.resolve(__dirname, '.env.local'), override: true });
// console.log('webpack-localEnv', localEnv.parsed, process.env);
console.log('webpack-localEnv', process.env);
module.exports = {
  mode: 'development',
  // plugins: [new webpack.DefinePlugin({ 'process.env': JSON.stringify(env) })],
  plugins: [
    // 读取.env, .env.local,env.development,env.production文件中的环境变量
    // new Dotenv(),
    // 在前端支持.env环境变量配置文件
    // new NodePolyfillPlugin(),
    // new webpack.DefinePlugin({ 'process.env': JSON.stringify(env.parsed) }),
    // 将运行时代码中的process.env.xx转化为相应的值
    new webpack.DefinePlugin({ 'process.env': JSON.stringify(process.env) }),
    // 生成html文件
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, 'public/index.html')
    })
  ],
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'main.js'
    // clean: true
  },
  devServer: {
    host: 'localhost',
    // open: true,
    open: false,
    port: 9000
  },
  module: {
    rules: [
      {
        test: /\.(js|ts|jsx|tsx)$/,
        include: [paths.appSrc, path.resolve(__dirname, 'envConfig')],
        use: [
          {
            loader: 'esbuild-loader',
            options: {
              loader: 'tsx',
              target: 'es2015'
            }
          }
        ]
      }
    ]
  },
  // 生成源码映射,方便找到出错的源码位置
  devtool: 'eval-cheap-module-source-map',
  resolve: {
    extensions: ['.js', '.ts', '.tsx', '.json', '.d.ts'],
    // 配置路径别名,一定要使用__dirname或path.resolve(__dirname, 'xx'),且需要配置tsconfig.json里面的路径
    // 使用相对路径,会出现找不到文件的错误
    alias: {
      // '@': './'
      '@': __dirname
    }
    // symlinks: false
  }
};
